<template>
  <div class="w1 h1" id="pie-chart"></div>
</template>
<script>
import { mapState } from "vuex";
const option = {
  tooltip: {
    trigger: "item",
    formatter: "{a} <br/>{b}: {c} ({d}%)"
  },
  legend: {
    orient: "vertical",
    x: "1",
    y: "center",
    textStyle: {
      color: "#fff"
    }
  },
  series: [
    {
      name: "实时功率",
      type: "pie",
      radius: ["60%", "80%"],
      center: ["70%", "50%"],
      avoidLabelOverlap: false,
      label: {
        normal: {
          show: false,
          position: "center"
        },
        emphasis: {
          show: true,
          textStyle: {
            fontSize: "12",
            fontWeight: "bold"
          }
        }
      },
      labelLine: {
        normal: {
          show: false
        }
      },
      data: [
        {
          value: 135,
          name: "视频广告",
          itemStyle: {
            color: "rgb(67,209,135)"
          }
        },
        {
          value: 1548,
          name: "搜索引擎",
          itemStyle: {
            color: "rgb(84,254,251)"
          }
        }
      ]
    }
  ]
};

export default {
  computed: {
    ...mapState({
      topList: state => state.cityInfo.topList
    })
  },
  mounted() {
    this._print();
  },
  data() {
    return {
      chart_pie: null
    };
  },
  watch: {
    topList: {
      deep: true,
      handler(val) {
        this._print();
      }
    }
  },
  methods: {
    _print() {
      let colorLists = ["rgb(255,104,3)", "rgb(84,254,251)", "rgb(10,240,118)"];
      this.$nextTick(_ => {
        if (!!this.chart_pie) this.chart_pie.clear();

        this.chart_pie = this.echarts.init(
          document.getElementById("pie-chart")
        );
        let options = {
          ...option
        };
        let data = null;
        try {
          data = this.topList.map((item, i) => {
            return {
              value: item.value,
              name: item.deviceName,
              itemStyle: {
                color: colorLists[i]
              },
              tooltip: {
                formatter: params => {
                  return `<span>${
                    this.topList[params.dataIndex].companyName
                  }</span><br/>
                  <span>${params.name}</span><br/>
                  <span>${params.value}kW</span>`;
                }
              }
            };
          });
          options.series[0].data = data;
          options.series[0].name = this.topList[0].companyName;

          this.chart_pie.setOption(options);
        } catch (e) {}
      });
    }
  }
};
</script>
